package org.springframework.cloud.netflix.feign;

import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.support.GenericApplicationContext;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.StringTokenizer;

@ConfigurationProperties("spring.active")
public class CodemaoFeignClientBeanListener implements ApplicationListener<ContextRefreshedEvent> {
    public static final Logger LOGGER = LoggerFactory.getLogger(CodemaoFeignClientBeanListener.class);

    private String services;

    @Setter
    private String profile;

    private String env = "production";

    public CodemaoFeignClientBeanListener(String services) {
        this.services = services;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //所有feign 服务
        GenericApplicationContext applicationContext = (GenericApplicationContext) event.getApplicationContext();
        String[] feignClientNames = applicationContext.getBeanNamesForType(FeignClientFactoryBean.class);
        if (services != null && feignClientNames != null && feignClientNames.length > 0) {
            LOGGER.info("spring.active.profile={}",profile);
            if (env.equalsIgnoreCase(profile)) {
                LOGGER.info("线上环境，不能直连，只能走注册中心");
                return;
            }
            StringTokenizer tokenServices = new StringTokenizer(services, ";");
            while (tokenServices.hasMoreElements()) {
                String service = tokenServices.nextToken();
                String serviceName = service.substring(0, service.indexOf(":")).trim();
                String url = service.substring(service.indexOf(":") + 1).trim();
                try {//check url is correct
                    new URL(url);
                } catch (MalformedURLException e) {
                    throw new IllegalArgumentException(url + "codemao.feign.debug.services 配置URL不对，请修改yaml配置文件", e);
                }
                //修改对应的服务为直连
                for (String feignClientName : feignClientNames) {//工厂bean，需要去掉&获取BeanDefinition
                    String beanName = feignClientName.substring(1);
                    BeanDefinition beanDefinition = applicationContext.getBeanDefinition(beanName);
                    String name = (String) beanDefinition.getPropertyValues().get("name");
                    if (serviceName.equalsIgnoreCase(name)) {// 查找到对应的服务，修改url
                        beanDefinition.getPropertyValues().add("url", url);
                        applicationContext.registerBeanDefinition(beanName, beanDefinition);
                    }
                }
            }

        }
    }


}
